package com.xgkj.diyiketang.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.hxsdk.DemoDBManager;
import com.xgkj.diyiketang.task.LogoutTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.yizhibo.Preferences;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private String TAG = getClass().getSimpleName();
    private Context mContext;

    private RelativeLayout updatePswLayout;
    private RelativeLayout clearCacheLayout;
    private RelativeLayout aboutLayout;
    private TextView mHuanCun;

    private static final String CACHE_FILE = "diyiketang/cache";
    private static final String APK_FILE = "diyiketang/apk";
    private static final String IMG_FILE = "diyiketang/img";
    private EatShowUserInfo userInfo;
    private TextView exitBtn;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        mContext = this;
        initView();
    }

    private void initView() {
        userInfo = getEatShowApp().getmUserInfo();
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        updatePswLayout = (RelativeLayout) findViewById(R.id.updatepsw_layout);
        updatePswLayout.setOnClickListener(this);
        clearCacheLayout = (RelativeLayout) findViewById(R.id.clearcache_layout);
        clearCacheLayout.setOnClickListener(this);
        aboutLayout = (RelativeLayout) findViewById(R.id.about_layout);
        aboutLayout.setOnClickListener(this);
        exitBtn = (TextView) findViewById(R.id.exit_btn);
        exitBtn.setOnClickListener(this);
        mHuanCun = (TextView) findViewById(R.id.huancun);
        try {
            String hc = getTotalCacheSize(mContext);
            mHuanCun.setText(hc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getTotalCacheSize(Context context) throws Exception {

//        long cacheSize = getFolderSize(context.getCacheDir());
        File file = EatShowSetting.getInstance(context).getDataFolder(CACHE_FILE);
        File apkFile = EatShowSetting.getInstance(context).getDataFolder(APK_FILE);
        File imgFile = EatShowSetting.getInstance(context).getDataFolder(IMG_FILE);

        long cacheSize = getFolderSize(file);
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        cacheSize += getFolderSize(apkFile);
        cacheSize += getFolderSize(imgFile);
//        }

        return getFormatSize(cacheSize);
    }

    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    private void showClearCacheDialog() {
        final ProgressDialog mProgress = DialogUtil.showProgressDialog(mContext, getString(R.string.do_clear_cache), false, null);
        File file = EatShowSetting.getInstance(mContext).getDataFolder(CACHE_FILE);
        if (file.exists()) {
            PalLog.e(TAG, file.getAbsolutePath() + "******" + file.getPath());
            delAllFile(file.getAbsolutePath());
        }

        File apkFile = EatShowSetting.getInstance(mContext).getDataFolder(APK_FILE);
        if (apkFile.exists()) {
            delAllFile(apkFile.getAbsolutePath());
        }

        File imgFile = EatShowSetting.getInstance(mContext).getDataFolder(IMG_FILE);
        if (imgFile.exists()) {
            delAllFile(imgFile.getAbsolutePath());
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mProgress.dismiss();
                ToastUtil.showMessage(mContext, R.string.clear_cache_success);
                mHuanCun.setText(null);
            }
        }, 2000);

    }

    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);
            }
        }
    }

    private void showExitDialog() {
        DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.exit_app), getString(R.string.ok), getString(R.string.cancle), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EatShowSetting.getInstance(mContext).setLoginName(null);
                EatShowSetting.getInstance(mContext).setLoginPsw(null);
                EatShowSetting.getInstance(mContext).setThirdNickname(null);
                EatShowSetting.getInstance(mContext).setThirdOpenid(null);
                EatShowSetting.getInstance(mContext).setThirdLogo(null);
                EatShowSetting.getInstance(mContext).setThirdType(-1);
//                getEatShowApp().exitApp();
                getEatShowApp().setmUserInfo(null);
                EMChatManager.getInstance().logout();
                DemoDBManager.getInstance().closeDB();
                doLogout();
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                getEatShowApp().finishAllActivity();
            }
        }, null);
    }

    private void doLogout() {
        LogoutTask task = new LogoutTask();
        getEatShowApp().getTaskManager().addTask(task);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.updatepsw_layout:

                if (userInfo != null) {
                    String openId = userInfo.getOpenId();
                    if (!TextUtils.isEmpty(openId)) {
                        ToastUtil.showMessage(mContext, R.string.no_need_updatepsw);
                        return;
                    }
                }
                Intent updatepsw_intent = new Intent(mContext, UpdatePasswordActivity.class);
                startActivity(updatepsw_intent);
                break;

            case R.id.clearcache_layout:
                showClearCacheDialog();
                break;

            case R.id.about_layout:
                Intent about_intent = new Intent(mContext, AboutActivity.class);
                startActivity(about_intent);
                break;
            case R.id.exit_btn:
                showExitDialog();
                break;

        }
    }
}
